package com.qining618.cms.cms.controller.app;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qining618.cms.cms.controller.app.request.AppCommentSaveRequest;
import com.qining618.cms.cms.domain.Comment;
import com.qining618.cms.cms.service.CommentService;
import com.qining618.common.annotation.Access;
import com.qining618.common.context.ContextHandle;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.TableData;
import com.qining618.common.utils.Query;
import com.qining618.common.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author flt
 * @date 2019-09-19
 */
@RestController
@RequestMapping("/app/api/cms/comment")
public class AppCommentController {

    @Autowired
    private CommentService commentService;

    @Access
    @PostMapping
    @Description("保存")
    public ApiResult save(
            HttpServletRequest request,
            @RequestBody @Validated AppCommentSaveRequest commentSaveRequest) {
        // 获取当前用户id
        Long userId = ContextHandle.getUserId();

        // 获取客户端真实ip
        String ip = RequestUtil.getIpAddr(request);

        // 保存
        Comment comment = commentService.save(userId, commentSaveRequest.getContentId(), commentSaveRequest.getText(),
                ip, commentSaveRequest.getParentId());
        return ApiResult.ok(comment.getId());
    }

    @Access
    @GetMapping("myList")
    @Description("我的评论列表")
    public ApiResult myList(Map<String, Object> params) {
        // 获取当前用户id
        Long userId = ContextHandle.getUserId();

        Query<Comment> query = new Query<>(params);
        query.getQueryWrapper().lambda().eq(Comment::getCommentUserId, userId);
        IPage<Comment> pageInfo = commentService.page(query.getPage(), query.getQueryWrapper());
        return ApiResult.ok(TableData.of(pageInfo));
    }

}
